#!/bin/bash
# Usage: build.sh [target_type]
# Author: han_gangbiao [jackhen]
# [http://my.oschina.net/jackhen]
# Date: 2015-10-20 18:36:37

targets[1]="linux-gcc-debug"
targets[2]="linux-gcc-release"
targets_total=2

target_type=$1
if [ -z "$target_type" ]; then
    for ((i=1; i<=targets_total; i++)); do
        echo "$i: ${targets[$i]}"
    done
    echo "Please choose target: "
    read idx
    target_type=${targets[$idx]}
    if [ -z "$target_type" ]; then
        echo "Err: bad choose."
        exit 1
    fi
fi

valid=0
for ((i=1; i<=targets_total; i++)); do
    if [ "$target_type" == "${targets[$i]}" ]; then
        valid=1
    fi
done
if [ "$valid" == "0" ]; then
    echo "Usage: build.sh <target_type>"
    exit 1
fi

set -x
BUILD_OPT=""
FN_D=""
if [ ${target_type:(-5)} == "debug" ]; then
    BUILD_OPT="$BUILD_OPT D=1"
    FN_D="_d"
fi

export LC_ALL=C
echo build at $(date)

make -C . $BUILD_OPT clean
make -C . $BUILD_OPT
if [ $? -ne 0 ]; then
    echo "Err: build failed.{smartrpc}"
    exit 1
fi

make -C ./test/tcpserver $BUILD_OPT clean
make -C ./test/tcpserver $BUILD_OPT
if [ $? -ne 0 ]; then
    echo "Err: build failed.{tcpserver}"
    exit 1
fi

make -C ./test/examples/concurrence $BUILD_OPT clean
make -C ./test/examples/concurrence $BUILD_OPT
if [ $? -ne 0 ]; then
    echo "Err: build failed.{concurrence}"
    exit 1
fi

make -C ./test/examples/latency $BUILD_OPT clean
make -C ./test/examples/latency $BUILD_OPT
if [ $? -ne 0 ]; then
    echo "Err: build failed.{latency}"
    exit 1
fi

make -C ./test/examples/throughput $BUILD_OPT clean
make -C ./test/examples/throughput $BUILD_OPT
if [ $? -ne 0 ]; then
    echo "Err: build failed.{throughput}"
    exit 1
fi

make -C ./test/examples/tpsclient $BUILD_OPT clean
make -C ./test/examples/tpsclient $BUILD_OPT
if [ $? -ne 0 ]; then
    echo "Err: build failed.{tpsclient}"
    exit 1
fi

DST_DIR=bin${FN_D}
rm -rf $DST_DIR
mkdir $DST_DIR

mkdir -p ./$DST_DIR/smartrpc_dist_pkg
mkdir -p ./$DST_DIR/smartrpc_dist_pkg/base
mkdir -p ./$DST_DIR/smartrpc_dist_pkg/net
mkdir -p ./$DST_DIR/smartrpc_dist_pkg/protocol
mkdir -p ./$DST_DIR/smartrpc_dist_pkg/rpc

cp -p ./base/*.h ./$DST_DIR/smartrpc_dist_pkg/base
cp -p ./net/*.h ./$DST_DIR/smartrpc_dist_pkg/net
cp -p ./protocol/*.h ./$DST_DIR/smartrpc_dist_pkg/protocol
cp -p ./rpc/*.h ./$DST_DIR/smartrpc_dist_pkg/rpc
cp -p ./libsmartrpc${FN_D}.a ./$DST_DIR/smartrpc_dist_pkg

cd ./$DST_DIR
tar -zcvf smartrpc_dist_pkg.tar.gz smartrpc_dist_pkg
cd -

cp -p ./test/tcpserver/tcpserver${FN_D} ./$DST_DIR
cp -p ./test/examples/concurrence/conclient${FN_D} ./$DST_DIR
cp -p ./test/examples/latency/latency${FN_D} ./$DST_DIR
cp -p ./test/examples/throughput/tpsserver${FN_D} ./$DST_DIR
cp -p ./test/examples/tpsclient/tpsclient${FN_D} ./$DST_DIR

